<?php
/**
 * 商品同步
 * User: poptser@foxmail.com
 * Date: 2018/3/5
 * Time: 9:07
 */
namespace App\Http\Controllers\WarehouseManage;

use App\Http\Controllers\ApiController;
use App\Services\Warehouse\MaterialService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;


class GoodsController extends ApiController{

    public  $goodsService;
    public function __construct(MaterialService $materialService)
    {
        //注入物料单实例
        $this->goodsService = $materialService;
    }


    public function getUpdateGoods(Request $request){
        $goodsSnList = $request->goods_sn;
        $goodsSnArray = explode(",",$goodsSnList);
        $goodsArray = [];
        if (count($goodsSnArray)>0){
            foreach ($goodsSnArray as $value){
                $oneGoodsInfo = $this->goodsService->DetailsMaterial($value);
                if($oneGoodsInfo){
                    $goodsInfo = $oneGoodsInfo[0];
                    $newResult = $this->updateGoods($goodsInfo);
                    if(empty($newResult)){
                        $goodsArray[] = $goodsInfo['FName']." [ ".$goodsInfo['FNumber']." ] 已是最新";
                    }
                }else{
                    $goodsArray[] = $value." <span style='color: red'>金蝶不存在</span>";
                }
            }
            return $this->success($goodsArray,"更新错误得如data");    //输出所查询到的商品
        }else{
            return $this->failed("请输入商品货号");
        }
    }

    /**
     * 获取品牌ID
     * Author:poptser@foxmail.com
     * @param $brandName
     * @return int|mixed
     */
    public function getBrandId($brandName){
        $brandId = DB::table("brand")->where("brand_name",$brandName)->value("brand_id");
        if(empty($brandId)){
            $brandId = DB::table('brand')->insertGetId(
                [
                    'brand_name' => $brandName
                ]
            );
        }
        return $brandId;
    }

    /**
     * 执行更新单个商品
     * Author:poptser@foxmail.com
     * @param array $goodsInfo
     * @return bool
     */
    public function updateGoods(array $goodsInfo){

        if($goodsInfo['FIsVmiBusiness']===true){
            $consignment = 1;
        }else{
            $consignment = 0;
        }
        $data = [
            'goods_name' => $goodsInfo['FName'], //商品名称
            'origin' => $goodsInfo['F_PAEZ_Text'],//产地
            'tax_rate' =>  $this->getRate($goodsInfo['FTaxRateId.FName']),//税率
            'spec_unit' =>  $goodsInfo['FStoreUnitID.FName'],//商品属性
            'goods_weight' =>  $this->getWeight($goodsInfo['FGROSSWEIGHT'],$goodsInfo['FWEIGHTUNITID.FName']),//商品重量Kg
            //'stock_price' =>  $goodsInfo['F_PAEZ_Combo'],//进货价格
            'temperature' =>  $this->temperature($goodsInfo['F_PAEZ_Combo']),//商品存放方式
            'expiration_date' =>    $this->getShelfLife($goodsInfo['F_PAEZ_Integer'],$goodsInfo['F_PAEZ_Combo1']),//商品保质期
            'supplier_code' =>    $goodsInfo['FDefaultVendor.FNumber'],//供应商编号
            'consignment' =>    $consignment,//代销与否
            'brand_id' =>    $this->getBrandId($goodsInfo['F_PAEZ_Assistant.FDataValue'])//品牌ID
        ];
        $result = DB::table('goods')
            ->where('goods_sn','=', $goodsInfo['FNumber'])
            ->update($data);
        if($result!=0){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 更新全部商品
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getGoodsUpdateAll(){
        $lastGetNewGoods = DB::table('goods_syn')->where("type",0)
            ->orderBy('date', 'desc')->value('date');

        if(empty($lastGetNewGoods)){
            $lastGetNewGoods = "2016-01-01 00:00:01";
        }
        $goodsArray = [];
        $where = "FModifyDate > '".$lastGetNewGoods."'";

        //循环取出所有商品数据
        $i=0;
        while (true){
            try{
                $GoodsList = $this->goodsService->ListMaterial(
                    $i*2000,'',2000,$where
                );
            }catch (Exception $exception){
                return $exception->getMessage();
            }

            if($GoodsList!==false){
                foreach ($GoodsList as $value){
                    //return $value;
                    $newResult = $this->updateGoods($value);
                    if($newResult===false){
                        $goodsArray[] = $value['FName']." [ ".$value['FNumber']." ]";
                    }
                }
            }
            $i++;
            if(count($GoodsList)<2000||$GoodsList==false){
                DB::table('goods_syn')->insert(
                    ['type' => 0, 'date' => date('Y-m-d H:i:s')]
                );
                break;  //已没有更多内容，跳出循环，写入本次更新值
            }
        }
        return $this->success($goodsArray,"本批次商品错误记录如data中");
    }


    /**
     * 写入单个新品
     * Author:poptser@foxmail.com
     * @param array $goodsSn
     * @return mixed
     */
    public function newGoods(array $goodsSn){
        $inDb = DB::table('goods')->where('goods_sn',$goodsSn['FNumber'])->count();
        $inDbData = [];
        if(empty($inDb)){
            //本地不存在此商品，准备同步
            if($goodsSn['FIsVmiBusiness']===true){
                $consignment = 1;
            }else{
                $consignment = 0;
            }
            $inDbData = [
                'goods_sn' => $goodsSn['FNumber'],
                'goods_name' => $goodsSn['FName'], //商品名称
                'consignment' => $consignment, //是否代销
                'origin' => $goodsSn['F_PAEZ_Text'],//产地
                //'origin' => $goodsSn['FWEIGHTUNITID.FName'],//产地
                'tax_rate' =>  $this->getRate($goodsSn['FTaxRateId.FName']),//税率
                'spec_unit' =>  $goodsSn['FStoreUnitID.FName'],//份/包/瓶
                'goods_weight' =>  $this->getWeight($goodsSn['FGROSSWEIGHT'],$goodsSn['FWEIGHTUNITID.FName']),//商品重量Kg
                //'stock_price' =>  $goodsSn['F_PAEZ_Combo'],//进货价格
                'temperature' =>  $this->temperature($goodsSn['F_PAEZ_Combo']),//商品存放方式
                'expiration_date' =>  $this->getShelfLife($goodsSn['F_PAEZ_Integer'],$goodsSn['F_PAEZ_Combo1']),//商品保质期
                'supplier_code' =>  $goodsSn['FDefaultVendor.FNumber'],//供应商编号
                'brand_id' =>  $this->getBrandId($goodsSn['F_PAEZ_Assistant.FDataValue']),//品牌ID
            ];
            return $inDbData;
        }else{
            return false;
        }
//        $result = DB::table('goods')->insert($inDbData);
//        if($result){
//            return true;
//        }else{
//            return false;
//        }
    }

    /**
     * 同步全部新品
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getGoodsNew(){
        set_time_limit(0);
        $lastGetNewGoods = DB::table('goods_syn')->where("type",1)
            ->orderBy('date', 'desc')->value('date');

        if(empty($lastGetNewGoods)){
            $lastGetNewGoods = "2016-01-01 00:00:01";
        }
        $goodsArray = [];
        $where = "FCreateDate > '".$lastGetNewGoods."'";
        //$where = "FCreateDate > '2016-01-01 00:00:01'";

        //循环取出所有商品数据
        $i=0;

        while (true){
            $oneGoodsList = $this->goodsService->ListMaterial(
                $i*1000,null,1000,$where
            );
            //return $oneGoodsList;
            $inDbData = [];
            if($oneGoodsList!==false){
                foreach ($oneGoodsList as $value){
                    $newResult = $this->newGoods($value);
                    if($newResult!==false){
                        $inDbData[] = $newResult;
                    }
                }
            }


            DB::table('goods')->insert($inDbData);
            $i++;
            if(count($oneGoodsList)<1000){
                DB::table('goods_syn')->insert(
                    ['type' => 1, 'date' => date('Y-m-d H:i:s')]
                );
                break;  //已没有更多内容，跳出循环，写入本次更新值
            }
        }
        //return $inDbData;
        return $this->success($goodsArray,"本批次商品错误记录如data中");
    }



    /**
     * 格式化 税率与重量
     * Author:poptser@foxmail.com
     * @param $taxRate
     * @return string
     */
    public function getRate($taxRate){
        preg_match_all('/\d+/',$taxRate,$arr);
        return join('',$arr[0]);    //税率
    }

    /**
     * 温度字符串转ID
     * Author:poptser@foxmail.com
     * @param string $text
     * @return int
     */
    public function temperature(string $text){
        switch ($text){
            case "常温":
                return 1;
                break;
            case "冷冻":
                return 2;
                break;
            case "冷藏":
                return 3;
                break;
        }
    }

    /**
     * 返回重量
     * Author:poptser@foxmail.com
     * @param $weight
     * @param $unit
     * @return float|int
     */
    public function getWeight($weight, $unit){
        switch ($unit){
            case "千克":
                return $weight;
                break;
            case "克":
                return $weight/1000;
                break;
            case "升":
                return $weight;
                break;
            case "毫升":
                return $weight/1000;
                break;
        }
    }

    /**
     * 转换保质期
     * Author:poptser@foxmail.com
     * @param $value
     * @param $unit
     * @return float|int
     */
    public function getShelfLife($value, $unit){
        switch ($unit){
            case "D":
                return $value;
                break;
            case "M":
                return $value*30;
                break;
            case "Y":
                return $value*365;
                break;
        }
    }
}